<template>
  <div class="gray-page resident-detail-page">
    <nav-bar :title="`组织信息${title}`"></nav-bar>
    <div class="resident-detail-main page-main">
      <van-sticky class="page-scroll" :offset-top="44">
        <van-form
          validate-trigger="onSubmit"
          :show-error="false"
          ref="from"
          input-align="right"
          error-message-align="right"
          :label-width="120"
          @failed="onFailed"
          @submit="onSubmit"
        >
          <van-field
            required
            name="organizationTypeName"
            v-model="formParams.organizationTypeName"
            label="组织类型"
            right-icon="arrow"
            :rules="rules.organizationTypeName"
            @click="dictOpenPopup('organizationType')"
          />
          <van-field
            required
            name="licenseNum"
            v-model="formParams.licenseNum"
            label="统一社会信用代码"
            placeholder="请输入"
            right-icon="arrow"
            class="van-field__right-icon-white"
            :maxlength="50"
            :rules="rules.licenseNum"
          />
          <van-field
            v-if="formParams.organizationType === '1'"
            required
            name="enterpriseCategoryName"
            v-model="formParams.enterpriseCategoryName"
            label="企业类别"
            right-icon="arrow"
            placeholder="请选择"
            :rules="rules.enterpriseCategoryName"
            @click="dictOpenPopup('enterpriseCategory')"
          />
          <van-field
            v-if="formParams.organizationType === '2'"
            required
            name="enterpriseCategoryName"
            v-model="formParams.enterpriseCategoryName"
            label="社会组织类别"
            right-icon="arrow"
            placeholder="请选择"
            :rules="rules.enterpriseCategoryName"
            @click="dictOpenPopup('enterpriseCategory')"
          />
          <van-field
            v-if="formParams.organizationType === '1'"
            required
            name="organizationName"
            v-model="formParams.organizationName"
            label="企业名称"
            :maxlength="50"
            right-icon="arrow"
            placeholder="请输入"
            class="van-field__right-icon-white"
            :rules="rules.organizationName"
          />
          <van-field
            v-if="formParams.organizationType === '2'"
            required
            name="organizationName"
            v-model="formParams.organizationName"
            label="社会组织名称"
            placeholder="请输入"
            right-icon="arrow"
            class="van-field__right-icon-white"
            :maxlength="50"
            :rules="rules.organizationName"
          />
          <van-field
            v-if="formParams.organizationType === '1'"
            required
            name="organizationAddress"
            v-model="formParams.organizationAddress"
            label="企业地址"
            placeholder="请输入"
            :maxlength="50"
            right-icon="arrow"
            class="van-field__right-icon-white"
            :rules="rules.organizationAddress"
          />
          <van-field
            v-if="formParams.organizationType === '2'"
            required
            name="organizationAddress"
            v-model="formParams.organizationAddress"
            label="住所"
            placeholder="请输入"
            right-icon="arrow"
            class="van-field__right-icon-white"
            :maxlength="50"
            :rules="rules.organizationAddress"
          />
          <van-field
            name="latitudeLongitude"
            v-model="formParams.latitudeLongitude"
            label="经纬度"
            right-icon="arrow"
            class="van-field__right-icon-white"
            :maxlength="50"
            :rules="rules.latitudeLongitude"
          />
          <van-field
            v-if="formParams.organizationType === '1'"
            required
            name="organizationPhone"
            v-model="formParams.organizationPhone"
            label="企业联系方式"
            placeholder="请输入"
            right-icon="arrow"
            class="van-field__right-icon-white"
            :rules="rules.organizationPhone"
          />
          <van-field
            v-if="formParams.organizationType === '2'"
            name="registrationNo"
            v-model="formParams.registrationNo"
            label="登记证号"
            right-icon="arrow"
            class="van-field__right-icon-white"
            :maxlength="20"
            :rules="rules.registrationNo"
          />
          <van-field
            v-if="formParams.organizationType === '1'"
            type="digit"
            name="organizationPersonNum"
            v-model="formParams.organizationPersonNum"
            label="企业员工数"
            right-icon="arrow"
            class="van-field__right-icon-white"
            :maxlength="5"
            :rules="rules.organizationPersonNum"
          />
          <van-field
            v-if="formParams.organizationType === '2'"
            name="registrationAuthority"
            v-model="formParams.registrationAuthority"
            label="登记管理机关"
            right-icon="arrow"
            class="van-field__right-icon-white"
            :maxlength="20"
            :rules="rules.registrationAuthority"
          />
          <van-field
            v-if="formParams.organizationType === '1'"
            required
            readonly
            clickable
            name="idTypeName"
            v-model="formParams.idTypeName"
            label="法定代表人证件类型"
            placeholder="请选择"
            right-icon="arrow"
            :rules="rules.idTypeName"
            @click="dictOpenPopup('idType')"
          />
          <van-field
            v-if="formParams.organizationType === '1'"
            required
            name="legalIdCard"
            v-model="formParams.legalIdCard"
            label="法定代表人证件号码"
            placeholder="请输入"
            right-icon="arrow"
            class="van-field__right-icon-white"
            :rules="formParams.idType === '111' ? rules.legalIdCard : rules.legalPassport"
          />
          <van-field
            required
            name="legalPersonName"
            v-model="formParams.legalPersonName"
            label="法定代表人姓名"
            placeholder="请输入"
            right-icon="arrow"
            class="van-field__right-icon-white"
            :maxlength="50"
            :rules="rules.legalPersonName"
          />
          <van-field
            v-if="formParams.organizationType === '1'"
            required
            name="legalPhone"
            v-model="formParams.legalPhone"
            label="法定代表人联系方式"
            placeholder="请输入"
            right-icon="arrow"
            class="van-field__right-icon-white"
            :rules="rules.legalPhone"
          />
          <van-field
            v-if="formParams.organizationType === '2'"
            name="officeAddress"
            v-model="formParams.officeAddress"
            label="办公地址"
            placeholder="请输入"
            right-icon="arrow"
            class="van-field__right-icon-white"
            :maxlength="50"
            :rules="rules.officeAddress"
          />
          <van-field
            v-if="formParams.organizationType === '2'"
            clickable
            name="approvalDate"
            v-model="formParams.approvalDate"
            label="批准日期"
            right-icon="arrow"
            :rules="rules.approvalDate"
            @click="dateOpenPopup('approvalDate')"
          />
          <van-field
            v-if="formParams.organizationType === '2'"
            readonly
            clickable
            name="certificateValidityDate"
            v-model="formParams.certificateValidityDate"
            label="证书有效期"
            right-icon="arrow"
            @click="showCalendar = true"
          />
          <van-calendar v-model="showCalendar" type="range" @confirm="calendarConfirm" />
          <van-field
            v-if="formParams.organizationType === '2'"
            required
            name="registeredCapital"
            type="digit"
            v-model="formParams.registeredCapital"
            label="注册资金"
            placeholder="请输入"
            right-icon="arrow"
            class="van-field__right-icon-white"
            :maxlength="5"
            :rules="rules.registeredCapital"
          />
          <van-field
            v-if="formParams.organizationType === '2'"
            required
            name="organizationStatusName"
            v-model="formParams.organizationStatusName"
            label="状态"
            placeholder="请选择"
            right-icon="arrow"
            :rules="rules.organizationStatusName"
            @click="dictOpenPopup('organizationStatus')"
          />
          <van-field
            v-if="formParams.organizationType === '2'"
            required
            name="idTypeName"
            v-model="formParams.idTypeName"
            label="负责人证件类型"
            right-icon="arrow"
            placeholder="请选择"
            :rules="rules.idTypeName"
            @click="dictOpenPopup('idType')"
          />
          <van-field
            v-if="formParams.organizationType === '2'"
            required
            name="legalIdCard"
            v-model="formParams.legalIdCard"
            label="负责人证件号码"
            placeholder="请输入"
            right-icon="arrow"
            class="van-field__right-icon-white"
            :maxlength="18"
            :rules="formParams.legalIdCard === '111' ? rules.legalIdCard : rules.legalPassport"
          />
          <van-field
            v-if="formParams.organizationType === '2'"
            required
            name="chargePersonName"
            v-model="formParams.chargePersonName"
            label="负责人姓名"
            placeholder="请输入"
            right-icon="arrow"
            class="van-field__right-icon-white"
            :rules="rules.chargePersonName"
          />
          <van-field
            v-if="formParams.organizationType === '2'"
            required
            name="legalPhone"
            v-model="formParams.legalPhone"
            label="负责人联系方式"
            placeholder="请输入"
            right-icon="arrow"
            class="van-field__right-icon-white"
            :maxlength="11"
            :rules="rules.legalPhone"
          />
          <van-field
            name="insurancePersonName"
            v-model="formParams.insurancePersonName"
            label="治保负责人姓名"
            right-icon="arrow"
            class="van-field__right-icon-white"
            :maxlength="50"
            :rules="rules.insurancePersonName"
          />
          <van-field
            name="insurancePersonPhone"
            v-model="formParams.insurancePersonPhone"
            label="治保负责人联系方式"
            right-icon="arrow"
            class="van-field__right-icon-white"
            :maxlength="11"
            :rules="rules.insurancePersonPhone"
          />
          <van-field
            v-if="formParams.organizationType === '1'"
            name="dangerousEnterprises"
            label="是否危化企业"
            required
            :rules="rules.dangerousEnterprises"
          >
            <template #input>
              <van-radio-group v-model="formParams.dangerousEnterprises" direction="horizontal">
                <van-radio v-for="(item, key) in dictData.yesNo" :key="key" :name="item.code">
                  {{ item.description }}
                </van-radio>
              </van-radio-group>
            </template>
          </van-field>
          <van-field
            v-if="formParams.organizationType === '1'"
            name="potentialSafetyTypeName"
            v-model="formParams.potentialSafetyTypeName"
            label="安全隐患类型"
            right-icon="arrow"
            :rules="rules.potentialSafetyTypeName"
            @click="dictOpenPopup('potentialSafetyType')"
          />
          <van-field
            required
            name="degreeConcernName"
            v-model="formParams.degreeConcernName"
            label="关注程度"
            right-icon="arrow"
            :rules="rules.degreeConcernName"
            @click="dictOpenPopup('degreeConcern')"
          />
          <van-field name="establishPartyOrganization" label="是否具备建立中央党组织条件">
            <template #input>
              <van-radio-group v-model="formParams.establishPartyOrganization" direction="horizontal">
                <van-radio v-for="(item, key) in dictData.yesNo" :key="key" :name="item.code">
                  {{ item.description }}
                </van-radio>
              </van-radio-group>
            </template>
          </van-field>
          <van-field name="havePartyOrganization" label="是否有中共党组织">
            <template #input>
              <van-radio-group v-model="formParams.havePartyOrganization" direction="horizontal">
                <van-radio v-for="(item, key) in dictData.yesNo" :key="key" :name="item.code">
                  {{ item.description }}
                </van-radio>
              </van-radio-group>
            </template>
          </van-field>
          <van-field
            name="partyPersonNum"
            type="digit"
            v-model="formParams.partyPersonNum"
            label="中共党员数量"
            right-icon="arrow"
            class="van-field__right-icon-white"
            :maxlength="5"
            :rules="rules.partyPersonNum"
          />
          <van-field name="haveUnion" label="是否有工会">
            <template #input>
              <van-radio-group v-model="formParams.haveUnion" direction="horizontal">
                <van-radio v-for="(item, key) in dictData.yesNo" :key="key" :name="item.code">
                  {{ item.description }}
                </van-radio>
              </van-radio-group>
            </template>
          </van-field>
          <van-field
            name="unionNum"
            type="digit"
            v-model="formParams.unionNum"
            label="工会会员数量"
            right-icon="arrow"
            class="van-field__right-icon-white"
            :maxlength="5"
            :rules="rules.unionNum"
          />
          <van-field name="haveCommunistYouthLeague" label="是否有共青团组织">
            <template #input>
              <van-radio-group v-model="formParams.haveCommunistYouthLeague" direction="horizontal">
                <van-radio v-for="(item, key) in dictData.yesNo" :key="key" :name="item.code">
                  {{ item.description }}
                </van-radio>
              </van-radio-group>
            </template>
          </van-field>
          <van-field
            name="communistYouthNum"
            type="digit"
            :maxlength="5"
            v-model="formParams.communistYouthNum"
            label="共青团团员数量"
            right-icon="arrow"
            class="van-field__right-icon-white"
            :rules="rules.communistYouthNum"
          />
          <van-field name="haveFederationWomen" label="是否有妇联组织">
            <template #input>
              <van-radio-group v-model="formParams.haveFederationWomen" direction="horizontal">
                <van-radio v-for="(item, key) in dictData.yesNo" :key="key" :name="item.code">
                  {{ item.description }}
                </van-radio>
              </van-radio-group>
            </template>
          </van-field>
          <van-field
            name="womenNum"
            v-model="formParams.womenNum"
            label="妇女数量"
            right-icon="arrow"
            class="van-field__right-icon-white"
            :rules="rules.womenNum"
          />
          <van-field
            v-if="formParams.organizationType === '2'"
            name="sourceFunds"
            v-model="formParams.sourceFunds"
            label="资金来源"
            right-icon="arrow"
            class="van-field__right-icon-white"
            :maxlength="50"
            :rules="rules.sourceFunds"
          />
          <van-field v-if="formParams.organizationType === '2'" name="overseasBackground" label="是否有境外背景">
            <template #input>
              <van-radio-group v-model="formParams.overseasBackground" direction="horizontal">
                <van-radio v-for="(item, key) in dictData.yesNo" :key="key" :name="item.code">
                  {{ item.description }}
                </van-radio>
              </van-radio-group>
            </template>
          </van-field>
          <div style="padding: 16px">
            <van-button block type="info" native-type="submit" :disabled="buttonDisabled">提交</van-button>
          </div>
        </van-form>
      </van-sticky>
    </div>
    <!-- 字典项 -->
    <van-popup v-model="dictPopupShow" round position="bottom" @close="dictValue = ''">
      <van-picker
        show-toolbar
        :default-index="dictData[dictType] && dictData[dictType].findIndex(o => o.code === dictValue)"
        :columns="dictData[dictType]"
        value-key="description"
        @cancel="dictPopupShow = false"
        @confirm="dictOnConfirm"
      />
    </van-popup>
    <!-- 日期 -->
    <van-popup v-model="datePopupShow" round position="bottom" @close="date = new Date()">
      <van-datetime-picker
        v-model="date"
        type="date"
        title="选择年月日"
        :min-date="minDate"
        :max-date="maxDate"
        :formatter="formatter"
        @cancel="datePopupShow = false"
        @confirm="dateOnConfirm"
      />
    </van-popup>
  </div>
</template>

<script>
import { mapState } from 'vuex'
import SelectPopup from '@/mixins/selectPopup'
import { FormParams } from './libs/organization'
import { phoneReg, passPortCardReg, idCardCheck, residentNameReg } from '@/libs/regexp'
import Resident from '@/api/resident'
export default {
  mixins: [SelectPopup],
  data() {
    const insurancePersonPhoneValidator = () => {
      return this.formParams.legalPersonPhone && phoneReg.test(this.formParams.legalPersonPhone)
    }
    const legalPhoneValidator = () => {
      return this.formParams.legalPhone && phoneReg.test(this.formParams.legalPhone)
    }
    const legalPersonNameValidator = () => {
      return this.formParams.legalPersonName && residentNameReg.test(this.formParams.legalPersonName)
    }
    const insurancePersonNameValidator = () => {
      return this.formParams.insurancePersonName && residentNameReg.test(this.formParams.insurancePersonName)
    }
    const chargePersonNameValidator = () => {
      return this.formParams.chargePersonName && residentNameReg.test(this.formParams.chargePersonName)
    }
    return {
      title: '采集',
      showCalendar: false,
      dictTypes:
        'yesNo,degreeConcern,organizationType,socialOrganizationsType,enterpriseCategory,potentialSafetyType,idType,organizationStatus,legalPersonIdType',
      buttonDisabled: false,
      formParams: new FormParams(),
      rules: {
        organizationTypeName: [{ required: true, message: '请选择组织类型', trigger: 'change' }],
        licenseNum: [
          { required: true, message: '请输入统一社会信用代码' },
          { validator: this.getCheck, message: '该统一社会信用代码已使用' }
        ],
        organizationCategoryName: [{ required: true, message: '请选择企业类别/社会组织类别', trigger: 'change' }],
        organizationName: [{ required: true, message: '请填写企业名称/社会组织名称', trigger: 'blur' }],
        organizationAddress: [{ required: true, message: '请填写企业地址/住所', trigger: 'blur' }],
        organizationPhone: [{ required: true, message: '请填写企业联系方式', trigger: 'blur' }],
        idTypeName: [{ required: true, message: '请选择法定代表人/负责人证件类型', trigger: 'change' }],
        legalIdCard: [
          { required: true, message: '请输入法定代表人/负责人证件号' },
          { validator: idCardCheck, message: '请输入正确的证件号' }
        ],
        legalPassport: [
          { required: true, message: '请输入法定代表人/负责人证件号' },
          { pattern: passPortCardReg, message: '请输入正确的证件号' }
        ],
        legalPersonName: [
          { required: true, message: '请填写法定代表人姓名', trigger: 'blur' },
          { type: 'string', validator: legalPersonNameValidator, trigger: 'blur' }
        ],
        legalPhone: [
          { required: true, message: '请填写法定代表人/负责人联系方式', trigger: 'blur' },
          { type: 'string', validator: legalPhoneValidator, trigger: 'blur' }
        ],
        insurancePersonName: [{ type: 'string', validator: insurancePersonNameValidator, trigger: 'blur' }],
        insurancePersonPhone: [{ type: 'string', validator: insurancePersonPhoneValidator, trigger: 'blur' }],
        dangerousEnterprises: [{ required: true, message: '请选择是否危化企业', trigger: 'change' }],
        degreeConcernName: [{ required: true, message: '请选择关注程度', trigger: 'change' }],
        registeredCapital: [{ type: 'number', yrequired: true, message: '请填写注册资金', trigger: 'blur' }],
        organizationStatusName: [{ required: true, message: '请选择状态', trigger: 'change' }],
        chargePersonName: [
          { required: true, message: '请填写负责人姓名', trigger: 'blur' },
          { type: 'string', validator: chargePersonNameValidator, trigger: 'blur' }
        ]
      }
    }
  },
  computed: {
    ...mapState({
      user: state => state.userInfo
    })
  },
  mounted() {
    // 字典项
    this.getDict(this.dictTypes)
  },
  methods: {
    // 表单 - 校验
    onFailed(errorInfo) {
      this.$refs.from.scrollToField(errorInfo.errors[0].name)
    },
    // 表单 - 提交
    onSubmit() {
      this.buttonDisabled = true
      this.formParams.regionCode = this.user.regionCode
      this.formParams.legalIdType = this.formParams.idType
      this.formParams.organizationCategory = this.formParams.enterpriseCategory
      console.log(JSON.stringify(this.formParams))
      Resident.BaseInfo.saveData(this.formParams)
        .then(res => {
          const { status } = res.data
          if (status === 0) {
            this.$router.push({
              path: '/page/message',
              query: {
                backTo: this.$route.query.type ? '-2' : '-1',
                title: this.$route.query.type ? '更新成功' : '提交成功'
              }
            })
          } else {
            this.$toast.fail(res.data.message)
          }
          this.buttonDisabled = false
        })
        .catch(() => {
          this.buttonDisabled = false
        })
    },
    // 校验统一社会信用代码
    getCheck() {
      return new Promise((resolve, reject) => {
        Resident.BaseInfo.checkLicenseNum({
          organizationCode: this.formParams.organizationCode,
          licenseNum: this.formParams.licenseNum
        }).then(res => {
          resolve(res.data.status === 0)
        })
      })
    },
    formatDate(date) {
      return `${date.getFullYear()}-${date.getMonth() + 1}-${date.getDate()}`
    },
    calendarConfirm(date) {
      const [start, end] = date
      this.showCalendar = false
      this.formParams.certificateValidityDate = `${this.formatDate(start)},${this.formatDate(end)}`
    }
  }
}
</script>

<style lang="less" scoped>
@import '~@/assets/style/resident/detail.less';
</style>
